<?php

namespace App\Http\Controllers\Admin\V1;

use App\Models\V1\Admin;
use Illuminate\Http\JsonResponse;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Events\Admin\V1\LoginEvent;
use Illuminate\Support\Facades\Auth;
use App\Extensions\Log\V1\InstanceLog;
use App\Exceptions\Admin\V1\AdminException;
use App\Http\Resources\Admin\V1\AdminResource;
use App\Http\Requests\Admin\V1\LoginLoginRequest;

//控制器编号01
class LoginController extends Controller
{
    /**
     * @param LoginLoginRequest $request
     * @return JsonResponse
     * @throws AdminException
     * @author 陈文小超
     * @maxim from专注to执行
     * @time 2021/3/24/15:10
     */
    public function login(LoginLoginRequest $request)
    {
        $credentials = $request->only(['username', 'password']);
        $credentials['is_enable'] = Admin::ENABLE_TRUE;
        if (!$login_token = Auth::guard($this->guard_type)->claims([$this->guard_type])->attempt($credentials)) {
            throw new AdminException(AdminException::ADMIN_LOGIN_RETRIEVE_INVALID);
        }
        $login_user = Auth::guard($this->guard_type)->user();

        // 登录日志
        InstanceLog::instance('admin')->info('【登录】成功日志记录:' . $login_user);

        // 登录事件
        event(new LoginEvent($login_user, $login_token));

        return $this->success($this->respondWithToken($login_token, $login_user));
    }

    /**
     * @return JsonResponse
     * @author 陈文小超
     * @maxim from专注to执行
     * @time 2021/3/24/10:40
     */
    public function logout()
    {
        JWTAuth::parseToken()->invalidate();
        $result = [
            'status'  => trans('admin/v1/controller.general.success_status'),
            'message' => trans('admin/v1/controller.login.logout_message')
        ];

        return $this->success($result);
    }

    /**
     * @param $login_token
     * @param $login_user
     * @return array
     * @author 陈文小超
     * @maxim from专注to执行
     * @time 2021/3/23/15:10
     */
    function respondWithToken($login_token, $login_user): array
    {
        return [
            'token_type'  => 'Bearer',
            'login_token' => $login_token,
            'expires_in'  => JWTAuth::factory()->getTTL() * 60,
            'user_info'   => new AdminResource($login_user),
        ];
    }
}
